/** Copyright 2014, Ross Mahony. Some rights reserved. See COPYING. */
package models

import java.util.Date
import java.sql.{ Date => SqlDate }

import play.api.db.slick.Config.driver.simple._
import scala.slick.lifted.Tag

case class EnergyUsage(id: Long, customerId: Long, 
  effectiveFrom: Date, effectiveTo: Date, usage: Double, cost: Double, commodityType: String)

/** EnergyUsage entity. */
class EnergyUsageTbl(tag: Tag) extends Table[EnergyUsage](tag, "ENRGY_USG") {
  implicit val dateColumnType = MappedColumnType.base[Date, Long](d => d.getTime, d => new Date(d))

  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def customerId = column[Long]("CUST_ID", O.NotNull)
  def effectiveFrom = column[Date]("EFF_FRM", O.NotNull)
  def effectiveTo = column[Date]("EFF_TO", O.NotNull)
  def usage = column[Double]("USG", O.NotNull)
  def cost = column[Double]("COST", O.NotNull)
  def commodityType = column[String]("TYP", O.NotNull) 

  def * = (id, customerId, effectiveFrom, effectiveTo, usage, cost, commodityType) <> 
    (EnergyUsage.tupled, EnergyUsage.unapply _)
}

/** EnergyUsage DAO */
object EnergyUsageDAO {
  
  val energyUsages = TableQuery[EnergyUsageTbl]
  
 /**
  * Retrieve a [[models.EnergyUsage]] by the id
  *
  * @param id EnergyUsage ID
  */
  def findById(id: Long)(implicit s: Session): Option[EnergyUsage] =
  energyUsages.where(_.id === id).firstOption

 /**
  * Retrieve [[models.EnergyUsage]] by the customer id
  *
  * @param id EnergyUsage ID
  */
  def findAllByCustomerIdAndCommodity(customerId: Long, commodityType: String)(implicit s: Session): List[EnergyUsage] = {
    energyUsages.where(_.customerId === customerId).where(_.commodityType === commodityType).list
  }

 /**
  * Count all energyUsages
  *
  * @param id EnergyUsage ID
  */
  def count(implicit s: Session): Int =
  Query(energyUsages.length).first

 /**
  * Insert a new [[models.EnergyUsage]]
  *
  * @param energyUsage 
  */
  def insert(energyUsage: EnergyUsage)(implicit s: Session) {
    energyUsages.insert(energyUsage)
  }

 /**
  * Insert a new [[models.EnergyUsage]] by ignoring auto inc column
  *
  * @param energyUsage 
  */
  def forceInsert(energyUsage: EnergyUsage)(implicit s: Session) {
    energyUsages.forceInsert(energyUsage)
  }

 /**
  * Delete all energyUsages
  */
  def deleteAll(implicit s: Session) {
    energyUsages.delete
  }
}
